<template>
  <up-card 
    :index="task.id"
    :title="task.title"
    title-color="#333333"
    title-size="16"
    :sub-title="truncateText(task.title, 10)"
    :border="false" 
    :shadow="true" 
    :clickable="clickable && !isDisabled"
    @click="handleCardClick"
    :class="{ 'task-disabled': isDisabled }"
  >
    <template #body>
      <!-- 任务描述 -->
      <up-text v-if="task.description" :text="truncateText(task.description, 100)" size="14" color="#666" lines="3" >
      </up-text>
      <!-- 任务信息展示 -->
      <view class="task-info">
        <!-- 任务奖励 -->
        <view class="task-reward">
          <up-text size="18" :text= "`+ ${task.points}`" color="#ff9500" bold class="points-text"></up-text>
          <up-icon customPrefix="iconfont" name="jinbi" size="20" color="#ff9500"></up-icon>
        </view>
        
        <!-- 任务分类和难度 -->
        <view class="task-meta">
          <up-tag :show="task.category_text !== null" :text="task.category_text" size="mini" plain plainFill color="#1989fa" borderColor="#1989fa"></up-tag>
          <up-tag :show="task.difficulty !== null" :text="task.difficulty" size="mini" plain plainFill color="#ff6700" borderColor="#ff6700"></up-tag>
          <up-tag :show="task.is_hot" text="热门" size="mini" plain plainFill color="#ee0a24" borderColor="#ee0a24"></up-tag>
        </view>
      </view>
    </template>
    
    <template #foot>
      <!-- 任务统计信息 -->
      <view class="task-stats">
        <up-text size="12" decoration="underline" :text="`已有 ${task.completed_count || 0} 人参与`" color="#999">
        </up-text>
        <up-text v-if="task.deadline" size="12" :text="`${formatDeadline(task.deadline)}截止`" color="#999" class="task-deadline">
        </up-text>
      </view>
    </template>
  </up-card>
</template>

<script>
import { defineComponent, computed } from 'vue';
import { useTaskStore } from '../store/task.js';
import { useUserStore } from '../store/user.js';
import { getTaskStatusText, formatTime } from '../utils/common.js';

export default defineComponent({
  name: 'TaskCard',
  props: {
    // 任务数据
    task: {
      type: Object,
      required: true,
      default: () => ({})
    },
    // 是否显示操作按钮
    showActions: {
      type: Boolean,
      default: true
    },
    // 是否可点击
    clickable: {
      type: Boolean,
      default: true
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    }
  },
  emits: ['click', 'accept', 'submit', 'detail', 'loginRequired'],
  setup(props, { emit }) {
    const taskStore = useTaskStore();
    const userStore = useUserStore();
    
    // 计算任务是否禁用
    const isDisabled = computed(() => {
      return props.disabled || ['expired', 'completed', 'canceled'].includes(props.task.status);
    });
    
    // 计算状态文本
    const statusText = computed(() => {
      return getTaskStatusText(props.task.status) || '未知';
    });
    
    // 计算状态类型
    const statusType = computed(() => {
      const statusMap = {
        'pending': 'primary',
        'ongoing': 'warning',
        'pending_review': 'success',
        'completed': 'success',
        'rejected': 'error',
        'expired': 'info',
        'canceled': 'info'
      };
      return statusMap[props.task.status] || 'default';
    });
    
    // 截断文本 - 现在up-text组件的lines属性会自动处理文本截断
    const truncateText = (text, maxLength) => {
      if (!text || text.length <= maxLength) return text;
      return text.substring(0, maxLength) + '...';
    };
    
    // 格式化截止时间
    const formatDeadline = (deadline) => {
      if (!deadline) return '';
      const now = new Date();
      const deadlineDate = new Date(deadline);
      
      // 如果截止时间在今天之前，显示已过期
      if (deadlineDate < now) {
        return '已过期';
      }
      
      // 否则显示剩余时间
      const diffDays = Math.ceil((deadlineDate - now) / (1000 * 60 * 60 * 24));
      if (diffDays <= 1) {
        return '今日截止';
      } else if (diffDays <= 7) {
        return `${diffDays}天后截止`;
      } else if (diffDays <= 14) {
        return `${diffDays}两周内截止`;
      } else {
        return formatTime(deadline, ' YYYY-MM-DD 日');
      }
    };
    
    // 获取状态按钮文本
    const getStatusButtonText = (status) => {
      const buttonTextMap = {
        'expired': '已过期',
        'canceled': '已取消',
        'rejected': '已拒绝'
      };
      return buttonTextMap[status] || '未知';
    };
    
    // 处理卡片点击
    const handleCardClick = () => {
      console.log('任务卡片点击:', props.task.id, props.task.title);
      if (props.clickable && !isDisabled.value) {
        emit('click', props.task);
        // 如果任务未领取或进行中，跳转到详情页
        if (props.task.status === 'pending' || props.task.status === 'ongoing') {
          emit('detail', props.task);
        }
      }
    };
    
    // 处理领取任务
    const handleAcceptTask = async () => {
      console.log('领取任务:', props.task.id, props.task.title);
      // 检查是否登录
      if (!userStore.isLoggedIn) {
        emit('loginRequired');
        return;
      }
      
      try {
        const result = await taskStore.acceptTask(props.task.id);
        if (result && result.success) {
          uni.showToast({ title: '任务领取成功', icon: 'success' });
          emit('accept', props.task);
        } else {
          uni.showToast({ title: result?.message || '任务领取失败', icon: 'none' });
        }
      } catch (error) {
        console.error('领取任务失败:', error);
        uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
      }
    };
    
    // 处理提交任务
    const handleSubmitTask = () => {
      console.log('提交任务:', props.task.id, props.task.title);
      // 检查是否登录
      if (!userStore.isLoggedIn) {
        emit('loginRequired');
        return;
      }
      
      emit('submit', props.task);
      // 跳转到任务提交页面
      uni.navigateTo({ url: `/pages/task-submit/task-submit?id=${props.task.id}` });
    };
    
    return {
      isDisabled,
      statusText,
      statusType,
      truncateText,
      formatDeadline,
      getStatusButtonText,
      handleCardClick,
      handleAcceptTask,
      handleSubmitTask
    };
  }
});
</script>

<style lang="scss" scoped>
// 使用uView Plus组件默认样式，确保内容正确显示
:deep(.up-card) {
  border-radius: 12px;
  margin-bottom: 12px;
  padding: 16px;
  
  &.task-disabled {
    opacity: 0.7;
  }
  
  // 调整标题行布局
  .up-card__header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
  }
}

.task-description {
  margin-bottom: 12px;
  line-height: 1.5;
}

.task-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 12px 1px;
}

.task-reward {
  display: flex;
  align-items: center;
  justify-content: center;
  
  .points-text {
    margin-left: 7px;
  }
}

.task-meta {
  display: flex;
  flex-wrap: nowrap;
  gap: 6px;
}

.task-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.task-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
  
  :deep(.up-button) {
    min-width: 80px;
  }
}

</style>